#
#  Copyright 2022 The Open Islands Authors. All Rights Reserved.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#
from pyoi.rpc import rpc_utils
from pyoi.runtime.types import RuntimeHeartbeat, RuntimeState, CommonResponse
from pyoi.runtime_env import RuntimeENV
from pyoi.util.base_utils import trys
from pyoi.util.log_utils import getLogger

LOGGER = getLogger()
HEARTBEAT_LOGGER = getLogger("heartbeat", append_level_log=False)
REPORT_LOGGER = getLogger("report", append_level_log=False)


class RPCClient(object):
    URI_PREFIX = None

    @classmethod
    def init(cls):
        cls.URI_PREFIX = f"/worker/{RuntimeENV.API_VERSION}/jobs/{RuntimeENV.JOB_ID}/tasks/{RuntimeENV.TASK_NAME}/{RuntimeENV.TASK_VERSION}/{RuntimeENV.ROLE}/runtime"

    @classmethod
    @trys(1)
    def get_config(cls) -> CommonResponse:
        LOGGER.info(f"get runtime config")
        response = rpc_utils.local_request(
            method="GET",
            endpoint=f"{cls.URI_PREFIX}",
            json_body={}
        )
        LOGGER.info(f"get runtime config done, code: {response.code}, message: {response.message}")
        return response

    @classmethod
    @trys(1)
    def report_heartbeat(cls, latest_heartbeat: RuntimeHeartbeat) -> CommonResponse:
        HEARTBEAT_LOGGER.info(f"report runtime lastest heartbeat")
        response = rpc_utils.local_request(
            method="PUT",
            endpoint=f"{cls.URI_PREFIX}/heartbeat",
            json_body=latest_heartbeat.to_dict(),
        )
        HEARTBEAT_LOGGER.info(
            f"report runtime lastest heartbeat done, code: {response.code}, message: {response.message}")
        return response

    @classmethod
    @trys(1)
    def report_state(cls, runtime_state: RuntimeState) -> CommonResponse:
        REPORT_LOGGER.info(f"report runtime state")
        response = rpc_utils.local_request(
            method="PUT",
            endpoint=cls.URI_PREFIX,
            json_body=runtime_state.to_dict(),
        )
        REPORT_LOGGER.info(f"report runtime state done, code: {response.code}, message: {response.message}")
        return response
